package com.zx.练习题.demo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class T5 {

    // 方法：读取文件内容，转换ASCII码值，并写入新文件
    public static void convertFile(String inputFilePath, String outputFilePath) throws IOException {
        // 读取文件内容
        String content = new String(Files.readAllBytes(Paths.get(inputFilePath)));

        // 正则表达式用于匹配\xXX格式的ASCII码值
        Pattern pattern = Pattern.compile("\\\\x[0-9a-fA-F]{2}");
        Matcher matcher = pattern.matcher(content);

        StringBuilder newContent = new StringBuilder();

        // 遍历匹配到的ASCII码值并进行转换
        while (matcher.find()) {
            String hex = matcher.group();
            String decimal = _16ToChar(hex);
            try {
                matcher.appendReplacement(newContent, decimal);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        matcher.appendTail(newContent);

        // 将转换后的内容写入新文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
            writer.write(newContent.toString());
        }
    }

    public static void main(String[] args) {
        String inputFilePath = "D:\\workspace\\luckSnow1989.github.io\\article\\5.云原生&云服务\\a.html";  // 输入文件路径
        String outputFilePath = "D:\\workspace\\luckSnow1989.github.io\\article\\5.云原生&云服务\\b.html";  // 输出文件路径

        try {
            convertFile(inputFilePath, outputFilePath);
            System.out.println("Conversion completed. Check the output file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //
    //public static void main(String[] args) throws UnsupportedEncodingException {
    //    System.out.println(_16ToChar("\\x42"));
    //}
    //
    public static String _16ToChar(String str) {
        char hexChar = (char) Integer.parseInt(str.substring(2), 16);
        return String.valueOf(hexChar);
    }
    //
    //public static String _10ToChar(String str) {
    //    char hexChar = (char) Integer.parseInt(str.substring(2), 16);
    //    return String.valueOf(hexChar);
    //}
}
